import paho.mqtt.client as mqtt

mqtt_client = mqtt.Client()
topic = "/xxx/yyy"


# 连接成功回调
def on_connect(mc, userdata, flags, rc):
    print('连接到 mqtt 服务器' + str(rc))
    # 订阅主题
    mc.subscribe(topic)


# 消息接收回调
def on_message(mc, userdata, msg):
    print(f'''收到消息${msg}''')


mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
# 设置遗嘱
mqtt_client.will_set(topic, payload="will", qos=0, retain=False)
# 连接服务器
mqtt_client.connect(
    # 地址
    "xxx.xxx.xxx.xxx",
    # 端口
    5432,
    # 超时
    60
)
# 发送消息
mqtt_client.publish(topic, payload="{aaa:bbb}", qos=2)
mqtt_client.loop_forever()

